<?php

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use App\Models\Product;
use App\Models\HotProduct;
use Encore\Admin\Controllers\AdminController;

class HotProductsController extends AdminController
{
    protected $title = '爆款商品';
    
    protected function grid()
    {
        $grid = new Grid(new HotProduct());
	
	    $grid->column('id', 'ID');
	    $grid->column('product_id', '商品')->display(function () {
	    	return $this->product->title;
	    });
	    $grid->column('is_today', '今日')->switch(config('site.grid.switch'));
	    $grid->column('is_enable', '启用')->switch(config('site.grid.switch'));
	    $grid->column('created_at', '创建')->display(function () {
	    	return (string)$this->created_at;
	    });
	    $grid->column('order', '排序')->editable();
	
	    $grid->disableRowSelector();
	    $grid->disableExport();
	    $this->gridActions($grid);

        return $grid;
    }
	
	protected function gridActions(Grid $grid)
	{
		$grid->actions(function (Grid\Displayers\Actions $actions) {
			$actions->disableView();
		});
	}
    
    protected function form()
    {
        $form = new Form(new HotProduct());
	
	    $form->radio('is_today', '今日爆款')->options(config('site.bool'))->default(true);
	    $form->radio('is_enable', '启用')->options(config('site.bool'))->default(true);
	
	    $form->select('product_id', '爆款商品')->options(function ($id) {
		    if ($product = Product::find($id)) {
			    return [$product->id => $product->title];
		    }
	    })->ajax('/admin/api/products')
		    ->creationRules('required|unique:hot_products')
		    ->updateRules('required|unique:hot_products,product_id,{{id}}');
	
	    $form->image('poster', '全图海报')->uniqueName();
	    $form->color('back_color', '背景颜色')->default('#C0E2E7');
	    
	    $form->text('title_alias', '商品别名');
	    $form->color('title_alias_color', '别名颜色')->default('#000000');
	    
	    $form->text('label_text', '海报标签');
	    $form->color('label_text_color', '标签文字颜色')->default('#ffffff');
	    $form->color('label_back_color', '标签背景颜色')->default('#fc2429');
	    
	    $form->number('order', '排序')
		    ->min(1)->default(1)
		    ->rules('required|regex:/[1-9]+/', [
			    'required' => '显示顺序为必填项',
			    'regex' => '显示顺序只能为正整数',
		    ]);
	    
        return $form;
    }
}
